<?php

namespace App\Library\Logic;

use App\Library\Requests\Base\BasePageRequest;
use App\Models\MessageListModel;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class MessageListLogic extends MessageListModel
{
    public static function add(int $userId, int $acceptId, string $content, bool $buyer): void
    {
        $id = self::query()->where(function (Builder $builder) use ($acceptId, $userId) {
            $builder->where(function (Builder $builder) use ($acceptId, $userId) {
                $builder->where('send_id', $userId)->where('accept_id', $acceptId);
            })->orWhere(function (Builder $builder) use ($acceptId, $userId) {
                $builder->where('send_id', $acceptId)->where('accept_id', $userId);
            });
        })->value('id');
        if (!is_null($id)) {
            self::updateById($id, [
                'status' => 0,
                'content' => $content,
                'sendBuyer' => $buyer,
                'sendId' => $userId,
                'acceptId' => $acceptId,
                'updateTime' => now(),
            ]);
        } else {
            self::insertForModel([
                'sendId' => $userId,
                'acceptId' => $acceptId,
                'sendBuyer' => $buyer,
                'content' => $content,
            ]);
        }
    }

    public static function messageList(BasePageRequest $request): array
    {
        $k = 'kf:' . USERID;
        $userId = cache()->has($k) ? cache($k)['sellerId'] : USERID;
        $paginate = self::query()->where(function (Builder $builder) use ($userId) {
            $builder->where('send_id', $userId)->orWhere('accept_id', $userId);
        })->orderByDesc('message_list.update_time')->paginate($request->limit, [
            'message_list.*',
            DB::raw('if(send_id=' . $userId . ',1,0) as my'),
            DB::raw('if((send_buyer=1&&send_id=' . $userId . ')||(send_buyer=0&&accept_id=' . $userId . '),1,0) as buyer')
        ]);
        foreach ($paginate->items() as $item) {
            $id = $item->send_id === $userId ? $item->accept_id : $item->send_id;
            $user = cache('user:' . $id) ?? ['avatar' => null, 'nickname' => random()];
            $item->avatar = $user['avatar'];
            $item->nickname = $user['nickname'];
            unsetObject($item, ['id', 'created_at', 'updated_at']);
        }
        return paginate($paginate);
    }

    /**
     * count
     * @return int
     */
    public static function count(): int
    {
        $k = 'kf:' . USERID;
        if (cache()->has($k)) {
            $count = 0;
            foreach (redis('keys', implode(':', ['consultCount', USERID, '*'])) as $val) $count += (int)cache($val);
            return $count;
        } else {
            return self::query()->where('accept_id', USERID)->where('status', 0)->count();
        }
    }

    /**
     * lastInfo
     * @param int $userId
     * @return Model
     */
    public static function lastInfo(int $userId): Model
    {
        $k = 'kf:' . USERID;
        $sellerId = cache()->has($k) ? cache($k)['sellerId'] : USERID;
        return self::query()->where(function (Builder $builder) use ($userId, $sellerId) {
            $builder->where(function (Builder $builder) use ($userId, $sellerId) {
                $builder->where('send_id', $userId)->where('accept_id', $sellerId);
            })->orWhere(function (Builder $builder) use ($userId, $sellerId) {
                $builder->where('send_id', $sellerId)->where('accept_id', $userId);
            });
        })->first(['content', 'created_at']);
    }
}
